/**
 * combineStyles
 * @param style         default style for the Component
 * @param themes        style themes predefined in Component
 * @param themeClasses  theme name for instance, separated in space, e.g. <Button themes="primary outline"/>
 * @param instanceStyle specific style for instance, e.g. <Button style={border:'none'} />
 * @returns {*}
 */
export const combineStyles = (style, themes = {}, themeClasses = '', instanceStyle = {}) => {

    let exports = Object.assign({}, style)

    Object.assign(exports, ...themeClasses.split(' ').map(theme => themes[theme]), instanceStyle)

    return exports
}

export const formatDate = (date, format) => {

    if (typeof date === 'string') {
        if (!/[\-|\s]/.test(date)) {
            date = parseInt(date);
        }
    }

    date = new Date(date);

    var map = {
        "M": date.getMonth() + 1, //月份
        "d": date.getDate(), //日
        "h": date.getHours(), //小时
        "m": date.getMinutes(), //分
        "s": date.getSeconds(), //秒
        "q": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds() //毫秒
    };

    format = format.replace(/([yMdhmsqS])+/g, function (all, t) {
        var v = map[t];
        if (v !== undefined) {
            if (all.length > 1) {
                v = '0' + v;
                v = v.substr(v.length - 2);
            }
            return v;
        }
        else if (t === 'y') {
            return (date.getFullYear() + '').substr(4 - all.length);
        }
        return all;
    });

    return format;

}

export const maskPhoneNumber = (phone) => {
    return phone.replace(phone.substr(3, 4), '****')
}

export const ellipsis = (text, max) => {
    if (!text) return "";
    return text.length <= max ? text : text.slice(0, max) + '...';
}

export const getAge = birthday => {
    // @param birthday date string | Date
    // @return year age

    let age

    const birthdayPeriods = formatDate(new Date(birthday), 'yyyy-MM-dd').split('-')
    const todayPeriods = formatDate(new Date(), 'yyyy-MM-dd').split('-')

    age = todayPeriods[0] - birthdayPeriods[0]

    if (age == 0) {

        return 1

    }

    if (todayPeriods[1] < birthdayPeriods[1]) {
        age--
    } else if (todayPeriods[1] == birthdayPeriods[1] || todayPeriods[2] < birthdayPeriods[2]) {
        age--
    }

    return age
}

export const parseWeekdays = days => {
    const dict = {
        '1': '一',
        '2': '二',
        '3': '三',
        '4': '四',
        '5': '五',
        '6': '六',
        '7': '日'
    }
    let text = []
    if (typeof days === 'string') {
        days = days.split(',')
    }
    days.forEach(function (d) {
        text.push(dict[d])
    })
    return text.join('，')
}

export const fixMoney = money => {
    return parseFloat(money).toFixed(2)
}